package com.jinzhending.comm;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;


import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.net.URISyntaxException;
import java.util.LinkedList;
import java.util.List;
/**
 * @ProjectName: LieIdle
 * @Package: com.jinzhending.comm
 * @Author: huat
 * @Date: 2020/4/11 14:49
 * @Version: 1.0
 */
public class HttpCliceUtils {
    /**
     * 发送请求工具类
     * @param url  请求路径
     * @param params  参数
     * @return
     */
    public static String getRequest(String url,List<NameValuePair> params){
        // 创建Httpclient对象,相当于打开了浏览器
        CloseableHttpClient  httpclient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        try {
            // 创建HttpGet请求，相当于在浏览器输入地址没敲回车
            URIBuilder uriBuilder = new URIBuilder(url);
            //添加参数
            uriBuilder.setParameters(params);
            HttpGet httpGet = new HttpGet(uriBuilder.build());

            // 执行请求，相当于敲完地址后按下回车。获取响应
            response = httpclient.execute(httpGet);
            // 判断返回状态是否为200
            if (response.getStatusLine().getStatusCode() == 200) {
                // 解析响应，获取数据
                String content = EntityUtils.toString(response.getEntity(), "UTF-8");
                return content;
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }catch (URISyntaxException e) {
            e.printStackTrace();
        } finally {
            if (response != null) {
                // 关闭资源
                try {
                    response.close();
                    // 关闭浏览器
                    httpclient.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }
        return null;
    }


}